package com.siping.并发.黑马并发实战.保护性暂停;

/**
 * @author Yang Xu
 * @date 2021/8/30 11:42
 * @description: 保护性暂停
 */
public class GuardedObject {
    private Object response;
    private final Object lock = new Object();

    public Object get() {
        synchronized (lock) {
            while (response == null) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return response;
        }
    }

    /**
     * 带超时时间
     * @param millis
     * @return
     */
    public Object get(long millis) {
        synchronized (lock) {
            long startTime = System.currentTimeMillis();
            long timePassed = 0;
            while (response == null && timePassed < millis) {
                long waitTime = millis - timePassed;
                try {
                    lock.wait(waitTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                timePassed = System.currentTimeMillis() - startTime;
            }
            return response;
        }
    }

    public void complete(Object response) {
        synchronized (lock) {
            this.response = response;
            lock.notifyAll();
        }
    }

    public static void main(String[] args) {
        GuardedObject guardedObject = new GuardedObject();
        Thread t1 = new Thread(() -> {
            String response = "ok";
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            guardedObject.complete(response);
        });
        t1.start();
        Object res = guardedObject.get(1100);
        System.out.println("执行结果: " + res);
    }
}
